import React, { useRef, useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from './ui/dialog';
import { Button } from './ui/button';
import { Label } from './ui/label';
import { Progress } from './ui/progress';
import { postmanToMarkdown } from '../lib/export-manager';
import ReactMarkdown from 'react-markdown';

interface PostmanImportModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: () => void; // 新增导入成功回调
  projectId: string;
  teamId: string;
  parentId?: string; // 根目录id，可选
  createDirectory: (name: string, parentId: string | null) => Promise<string>;
  createDoc: (name: string, content: string, parentId: string | null) => Promise<void>;
}

// 递归导入 Postman item
async function importPostmanItems(
  items: any[],
  parentId: string | null,
  createDirectory: (name: string, parentId: string | null) => Promise<string>,
  createDoc: (name: string, content: string, parentId: string | null) => Promise<void>,
  setProgress?: (v: number) => void,
  totalCount?: number,
  doneCount?: { current: number }
) {
  for (const item of items) {
    if (item.item) {
      // 目录
      const dirId = await createDirectory(item.name, parentId);
      await importPostmanItems(item.item, dirId, createDirectory, createDoc, setProgress, totalCount, doneCount);
    } else if (item.request) {
      // 接口
      const docName = item.name;
      // 使用 postmanToMarkdown 生成 markdown 文本
      const docContent = postmanToMarkdown({ item: [item] });
      await createDoc(docName, docContent, parentId);
    }
    if (setProgress && totalCount && doneCount) {
      doneCount.current++;
      setProgress(Math.round((doneCount.current / totalCount) * 100));
    }
  }
}

function countPostmanItems(items: any[]): number {
  let count = 0;
  for (const item of items) {
    if (item.item) {
      count += countPostmanItems(item.item);
    } else if (item.request) {
      count++;
    }
  }
  return count;
}

const PostmanImportModal: React.FC<PostmanImportModalProps> = ({
  isOpen,
  onClose,
  onSuccess,
  projectId,
  teamId,
  parentId,
  createDirectory,
  createDoc,
}) => {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [progress, setProgress] = useState(0);
  const [error, setError] = useState<string | null>(null);
  const [importing, setImporting] = useState(false);
  const [step, setStep] = useState<'select' | 'postman'>('select');
  const [markdown, setMarkdown] = useState<string | null>(null);

  // 重置状态
  React.useEffect(() => {
    if (isOpen) {
      setStep('select');
      setProgress(0);
      setError(null);
      setImporting(false);
    }
  }, [isOpen]);

  // 选择文件并导入
  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setError(null);
    setProgress(0);
    setImporting(true);
    try {
      const text = await file.text();
      const json = JSON.parse(text);
      if (!json.info?.schema?.includes('v2.1')) {
        setError('只支持 Postman v2.1 版本的集合文件');
        setImporting(false);
        return;
      }
      // 新增：生成 markdown 预览
      setMarkdown(postmanToMarkdown(json));
      const items = json.item;
      const total = countPostmanItems(items);
      const doneCount = { current: 0 };
      const rootDirName = json.info?.name || 'Postman导入';
      const rootDirId = await createDirectory(rootDirName, parentId || null);
      await importPostmanItems(
        items,
        rootDirId,
        createDirectory,
        createDoc,
        setProgress,
        total,
        doneCount
      );
      setProgress(100);
      setTimeout(() => {
        setImporting(false);
        if (onSuccess) onSuccess(); // 导入成功后回调
        onClose();
      }, 800);
    } catch (err: any) {
      setError('导入失败：' + (err.message || '未知错误'));
      setImporting(false);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>导入</DialogTitle>
        </DialogHeader>
        <div className="space-y-4">
          {step === 'select' && (
            <>
              <Label className="text-sm font-medium">请选择导入平台</Label>
              <Button className="w-full" onClick={() => setStep('postman')}>
                导入 Postman 接口文档
              </Button>
              {/* 预留：后续可加更多平台 */}
            </>
          )}
          {step === 'postman' && (
            <>
              <Label className="text-sm font-medium">请选择 Postman v2.1 JSON 文件</Label>
              <input
                type="file"
                accept="application/json"
                ref={fileInputRef}
                onChange={handleFileChange}
                disabled={importing}
              />
              {importing && <Progress value={progress} />}
              {error && <div className="text-red-500 text-sm">{error}</div>}
              <Button variant="outline" className="mt-2" onClick={() => setStep('select')} disabled={importing}>
                返回平台选择
              </Button>
            </>
          )}
          {markdown && (
            <div className="mt-4">
              <Label className="text-sm font-medium">Markdown 预览</Label>
              <div className="markdown-preview" style={{ maxHeight: '320px', overflow: 'auto', border: '1px solid #eee', borderRadius: 4, padding: 8, background: '#f9f9f9' }}>
                <ReactMarkdown>{markdown}</ReactMarkdown>
              </div>
            </div>
          )}
        </div>
        <div className="flex justify-end gap-3 pt-4">
          <Button variant="outline" onClick={onClose} disabled={importing}>
            取消
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default PostmanImportModal;

/*
.markdown-preview table {
  table-layout: auto;
  min-width: 0;
  width: 100%;
}
.markdown-preview th, .markdown-preview td {
  word-break: break-all;
  padding: 4px 8px;
  border: 1px solid #ddd;
}
*/ 